/*
Copyright (C) 2010  Christoph Schnack, Berlin (Germany)

This file is part of Tribuit.

    Tribuit is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Tribuit is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Tribuit.  If not, see <http://www.gnu.org/licenses/>.
*/
package PictureMappingInterrogation;

import GuiTools.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import java.awt.*;
import java.awt.event.*;

import Mainframe.Mainframe;
import PictureDescription.*;
import Settings.*;

/**
 * @author Christoph Schnack
 *
 */
public class PictureMappingInterrogationSettings {
	MDTribuitFrame pmisFrame;
	Settings SET;
	Language LANG;
	PictureStorage PICSTO;
	Options options;
	SelectionPanel selectionPanel;
	MDManager PIDM;
	HashMap<String,Lesson> lessons;
	Vector<String> lessonNames;
	public PictureMappingInterrogationSettings(Mainframe mf,Settings set,PictureStorage picsto,MDManager pidm){
		SET = set;
		LANG = set.getLanguage();
		PIDM = pidm;
		PICSTO = picsto;
		options = new Options();
		lessons = PICSTO.getLessons();
		lessonNames = new Vector<String>();
		for(String s : lessons.keySet().toArray(new String[]{})){
			if(lessons.get(s).hasUnits()) lessonNames.add(s);
		}
		buildGui();
	}
	
	private void buildGui(){
		pmisFrame = new MDTribuitFrame(LANG.getPresettings(),PIDM);
		JPanel centerPanel = new JPanel(new GridBagLayout()),buttonPanel = new JPanel();
		JButton startBtn = new JButton(LANG.getStart());
		startBtn.addActionListener(new StartBtnListener());
		JButton cancelBtn = new JButton(LANG.getCancel());
		cancelBtn.addActionListener(new CancelBtnListener());
		buttonPanel.setBackground(GuiTools.BGCOLOR);
		buttonPanel.add(startBtn);
		buttonPanel.add(cancelBtn);
		
		GridBagConstraints gbc = new GridBagConstraints();
		gbc.anchor = GridBagConstraints.SOUTH;
		gbc.fill = GridBagConstraints.BOTH;
		selectionPanel = new SelectionPanel();
		gbc.insets = new Insets(10,10,10,10);
		gbc.gridy = 1;
		centerPanel.add(new OptionPanel(),gbc);
		gbc.gridy = 2;
		centerPanel.add(selectionPanel,gbc);
		centerPanel.setBackground(Color.gray);
		
		Container pane = pmisFrame.getContentPane();
		pane.add(BorderLayout.NORTH,new Header(LANG.getPresettings()));
		pane.add(BorderLayout.CENTER,centerPanel);
		pane.add(BorderLayout.SOUTH,buttonPanel);
		pmisFrame.showUp(100,100);
	}
	
	private class StartBtnListener implements ActionListener{
		public void actionPerformed(ActionEvent e){
			if(selectionPanel.hasElements()){
				pmisFrame.dispose();
				new PictureMappingInterrogation(SET,PICSTO,PIDM,selectionPanel.getContent(),options);
			}
			else{
				JOptionPane.showMessageDialog(pmisFrame, LANG.getPleaseSelectAtLeastOnePU(),LANG.getAttention(),JOptionPane.WARNING_MESSAGE);
			}
		}
	}
	
	private class CancelBtnListener implements ActionListener{
		public void actionPerformed(ActionEvent e){
			pmisFrame.dispose();
		}
	}
	
	public class Options{
		boolean regardCase=false;
		public boolean getRegardCase(){ return regardCase;}
		public void setRegardCase(boolean arg){ regardCase = arg;}
	}
	
	class OptionPanel extends JPanel{
		
		public OptionPanel(){
			super(new FlowLayout(FlowLayout.LEFT));
			final JCheckBox regardCaseCB = new JCheckBox(LANG.getCaseSensitivity());
			regardCaseCB.addActionListener(new ActionListener(){
				public void actionPerformed(ActionEvent e){
					options.setRegardCase(regardCaseCB.isSelected());
				}
			});
			this.add(regardCaseCB);
			this.setBorder(BorderFactory.createTitledBorder(LANG.getOptions()));
		}
	}
	
	class SourcePanel extends JPanel{
		PreviewPanel previewPanel;
		JComboBox lessonCB,collectionCB,sectionCB;
		JRadioButton allRB = new JRadioButton(LANG.getAll(),true), sectionRB = new JRadioButton();
		MyListModel listModel;
		JList list;
		public SourcePanel(){
			super(new GridBagLayout());
			listModel = new MyListModel();
			list = new JList(listModel);
			list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
			list.addListSelectionListener(new ListSelectionListener(){
				public void valueChanged(ListSelectionEvent arg0) {
					String value = (String)list.getSelectedValue();
					if(value!=null){
						String coll = (String)collectionCB.getSelectedItem();
						previewPanel.setImage(coll,value);
					}
					else previewPanel.setNoImage();
				}
			});;
			list.addMouseListener(new MouseAdapter(){
				public void mouseClicked(MouseEvent e){
					if(e.getClickCount()>=2){
						String selection = (String)list.getSelectedValue();
						if(selection!=null){
							selectionPanel.addElement((String)collectionCB.getSelectedItem()+": "+selection);
						}
					}
				}
			});
			
			Vector<String> names = new Vector<String>();
			for(String s : PICSTO.getCollectionNames()){
				if(PICSTO.getCollection(s).hasPictures()) names.add(s);
			}
			collectionCB = new JComboBox(names);
			collectionCB.setPreferredSize(new Dimension(100,collectionCB.getPreferredSize().height));
			collectionCB.addActionListener(new ActionListener(){
				public void actionPerformed(ActionEvent e){
					listModel.removeAllElements();
					String selection = (String)collectionCB.getSelectedItem();
					sectionCB.removeAllItems();
					for(String s : PICSTO.getCollection(selection).getSections()){
						sectionCB.addItem(s);
					}
					if(allRB.isSelected()){
						allRB.doClick();
					}
					else{
						sectionRB.doClick();
					}
				}
			});
			allRB.addActionListener(new ActionListener(){
				public void actionPerformed(ActionEvent e){
					sectionCB.setEnabled(false);
					listModel.removeAllElements();
					String selection = (String)collectionCB.getSelectedItem();
					for(PictureUnit pu : PICSTO.getCollection(selection).getPictureUnits()){
						listModel.addElement(pu.getName());
					}
				}
			});
			sectionRB.addActionListener(new ActionListener(){
				public void actionPerformed(ActionEvent e){
					sectionCB.setEnabled(true);
					listModel.removeAllElements();
					String selection = (String)collectionCB.getSelectedItem();
					String section = (String)sectionCB.getSelectedItem();
					for(PictureUnit pu : PICSTO.getCollection(selection).getPictureUnits()){
						if(pu.getSection().equals(section))listModel.addElement(pu.getName());
					}
				}
			});
			ButtonGroup bg = new ButtonGroup();
			bg.add(allRB);
			bg.add(sectionRB);
			sectionCB = new JComboBox();
			sectionCB.setPreferredSize(new Dimension(100,sectionCB.getPreferredSize().height));
			JPanel collPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
			collPanel.add(collectionCB);
			collPanel.add(allRB);
			collPanel.add(sectionRB);
			collPanel.add(sectionCB);
			previewPanel = new PreviewPanel(LANG.getPreview());
			JScrollPane listJsp = new JScrollPane(list);
			listJsp.setPreferredSize(previewPanel.getPreferredSize());
			JPanel listPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
			listPanel.add(listJsp);
			listPanel.add(previewPanel);
			//JPanel collectionPanel = new JPanel(new GridBagLayout());
			GridBagConstraints gbc = new GridBagConstraints();
			gbc.anchor = GridBagConstraints.SOUTHWEST;
			gbc.fill = GridBagConstraints.NONE;
			gbc.weighty=1;
			this.add(collPanel,gbc);
			gbc.gridy=1;
			this.add(listPanel,gbc);
			this.setBorder(BorderFactory.createTitledBorder(LANG.getCollections()));
			collectionCB.setSelectedIndex(0);
		}
	}
	
	class SelectionPanel extends JPanel{
		JList list;
		DefaultListModel listModel;
		PreviewPanel previewPanel;
		JComboBox lessonCB;
		public SelectionPanel(){
			super();
			listModel = new MyListModel();
			list = new JList(listModel);
			list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
			list.addListSelectionListener(new ListSelectionListener(){
				public void valueChanged(ListSelectionEvent arg0) {
					String value = (String)list.getSelectedValue();
					if(value!=null){
						String[] split = value.split(":");
						previewPanel.setImage(split[0], split[1].trim());
					}
					else previewPanel.setNoImage();
				}
			});;
			list.addMouseListener(new MouseAdapter(){
				public void mouseClicked(MouseEvent e){
					if(e.getClickCount()>=2){
						String value = (String)list.getSelectedValue();
						if(value!=null){
							listModel.removeElement(value);
						}
					}
				}
			});
			JButton clearBtn = new JButton(LANG.getClearList());
			clearBtn.addActionListener(new ActionListener(){
				public void actionPerformed(ActionEvent e){
					listModel.removeAllElements();
				}
			});
			JButton removeDuplicatesBtn = new JButton(LANG.getRemoveDuplicates());
			removeDuplicatesBtn.addActionListener(new ActionListener(){
				public void actionPerformed(ActionEvent e){
					String s,t;
					for(int i=0;i<listModel.size();i++){
						s = (String)listModel.elementAt(i);
						for(int r=listModel.size()-1;r>i;r--){
							t = (String)listModel.elementAt(r);
							if(s.equals(t)) listModel.removeElementAt(r);
						}
					}
				}
			});
			lessonCB = (lessonNames.size()>0)?new JComboBox(lessonNames):new JComboBox();
			lessonCB.setPreferredSize(new Dimension(120,lessonCB.getPreferredSize().height));
			JButton addBtn = new JButton(LANG.getAdd());
			addBtn.addActionListener(new ActionListener(){
				public void actionPerformed(ActionEvent e){
					Lesson lesson = lessons.get((String)lessonCB.getSelectedItem());
					for(String coll : lesson.getCollectionNames()){
						for(String unit : lesson.getUnitNames(coll)){
							selectionPanel.addElement(coll+": "+unit);
						}
					}
				}
			});
			lessonCB.setEnabled(lessonNames.size()>0);
			addBtn.setEnabled(lessonNames.size()>0);
			JPanel lessonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
			lessonPanel.add(lessonCB);
			lessonPanel.add(addBtn);
			//LabelPanel lessonLabelPanel = new LabelPanel(LANG.getLessons(),lessonPanel);
			JPanel buttonsPanel = new JPanel();
			buttonsPanel.add(lessonPanel);
			buttonsPanel.add(clearBtn);
			buttonsPanel.add(removeDuplicatesBtn);
			previewPanel = new PreviewPanel(LANG.getPreview());
			JScrollPane jsp = new JScrollPane(list);
			jsp.setPreferredSize(previewPanel.getPreferredSize());
			GridBagConstraints gbc = new GridBagConstraints();
			JPanel destPanel = new JPanel(new GridBagLayout());
			destPanel.setBorder(BorderFactory.createTitledBorder(LANG.getMapsForTest()));
			gbc.anchor = GridBagConstraints.NORTHWEST;
			gbc.fill = GridBagConstraints.NONE;
			gbc.gridwidth = 2;
			gbc.gridx = 1;
			gbc.gridy = 1;
			destPanel.add(buttonsPanel,gbc);
			gbc.gridwidth = 1;
			gbc.gridy = 2;
			destPanel.add(jsp,gbc);
			gbc.gridx = 2;
			destPanel.add(previewPanel,gbc);
			this.add(destPanel);
			this.add(new SourcePanel());
			this.setBorder(BorderFactory.createTitledBorder(LANG.getPictureMaps()));
		}
		
		public void clearList(){
			listModel.removeAllElements();
		}
		
		public void addElement(String s){
			listModel.addElement(s);
		}
		
		public boolean hasElements(){
			return !listModel.isEmpty();
		}
		
		public boolean containsElement(String s){
			return listModel.contains(s);
		}
		
		public HashMap<String,Vector<String>> getContent(){
			if(hasElements()){
				String[] array = new String[listModel.size()]; 
				listModel.copyInto(array);
				HashMap<String,Vector<String>> hm = new HashMap<String,Vector<String>>();
				String[] split;
				for(String s : array){
					split = s.split(":");
					if(!hm.containsKey(split[0])){
						hm.put(split[0],new Vector<String>());
					}
					hm.get(split[0]).add(split[1].trim());
				}
				return hm;
			}
			else return null;
		}
	}
	
	class MyListModel extends DefaultListModel{
		public MyListModel(){
			super();
		}
	}
}
